package com.example.himalaya2;

import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.himalaya2.adapters.RecommendListAdapter;
import com.example.himalaya2.adapters.SearchRecommendAdapter;
import com.example.himalaya2.base.BaseActivity;
import com.example.himalaya2.base.BaseApplication;
import com.example.himalaya2.interfaces.ISearchCallback;
import com.example.himalaya2.presenters.AlbumDetailPresenter;
import com.example.himalaya2.presenters.SearchPresenters;
import com.example.himalaya2.utils.Constants;
import com.example.himalaya2.utils.LogUtil;
import com.example.himalaya2.views.FlowTextLayout;
import com.example.himalaya2.views.UILoader;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.ximalaya.ting.android.opensdk.model.album.Album;
import com.ximalaya.ting.android.opensdk.model.album.AlbumList;
import com.ximalaya.ting.android.opensdk.model.word.HotWord;
import com.ximalaya.ting.android.opensdk.model.word.QueryResult;

import net.lucode.hackware.magicindicator.buildins.UIUtil;

import org.jetbrains.annotations.NotNull;
import com.example.himalaya2.utils.Constants;
import java.util.ArrayList;
import java.util.List;

public class SearchActivity  extends BaseActivity implements ISearchCallback ,RecommendListAdapter.OnRecommendItemClickListener{

    private View mBackBtn;
    private EditText mInputBox;
    private TextView mSearchBtn;
    private FrameLayout mSearchContainer;

    public static final String TAG = "SearchActivity";
    private SearchPresenters mSearchPresenters;
    private UILoader mContainer;
    private RecyclerView mResultListView;
    private RecommendListAdapter mAlbumAdapter;
    private View mDeleteInputV;
    private FlowTextLayout mFlowTextLayout;
    private InputMethodManager mInputMethodManager;
    private RecyclerView mRecommendRc;
    private SearchRecommendAdapter mRecommendAdapter;
    private RefreshLayout mRefreshLayout = null;
    private boolean mNeedSuggest = true;
    //private FlowTextLayout mFlowTextLayout;


    @Override
    protected void onCreate(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        mInputMethodManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
        initView();
        initEven();
        initPresenter();
    }

    private void initPresenter() {
        mSearchPresenters = SearchPresenters.getInstance();
        mSearchPresenters.registerViewCallback(this);
        // 去拿热词
        mSearchPresenters.getHotWord();
    }

    private void initEven() {
        mAlbumAdapter.setOnRecommendItemClickListener(this);
        if (mRecommendAdapter != null) {
            mRecommendAdapter.setItemClickListener(new SearchRecommendAdapter.ItemClickListener() {
                @Override
                public void onItemClick(String keyWord) {
                    LogUtil.d(TAG,"mRecommendAdapter keyword:" + keyWord);
                    // 去执行搜索动作
                    // 推荐热词的点击
                    // 不需要相关的联想
                    mNeedSuggest = false;
                    switch2Search(keyWord);

                }
            });
        }
        mBackBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        mSearchBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //
               String keyWord =  mInputBox.getText().toString().trim();
                if (TextUtils.isEmpty(keyWord)) {
                    Toast.makeText(SearchActivity.this ,"搜索内容不内为空",Toast.LENGTH_SHORT).show();
                } else {
                    if (mSearchPresenters != null) {
                        mSearchPresenters.doSearch(keyWord);
                        mContainer.updateStatus(UILoader.UIStatus.LOADING);
                    }
                }
            }
        });
        mInputBox.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                LogUtil.d(TAG,"CONTENT:"+charSequence);
                if (TextUtils.isEmpty(charSequence)) {
                    if (mSearchPresenters != null) {
                        mSearchPresenters.getHotWord();
                        mDeleteInputV.setVisibility(View.GONE);
                    }
                } else {
                    mDeleteInputV.setVisibility(View.VISIBLE);
                    // 输入框 不为空的时候，触发联想查询
                    if (mNeedSuggest) {
                        getSuggestWord(charSequence);
                    } else {
                        mNeedSuggest = true;
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        mFlowTextLayout.setClickListener(new FlowTextLayout.ItemClickListener() {
            @Override
            public void onItemClick(String text) {
                // 不需要相关的联想
                mNeedSuggest = false;
                switch2Search(text);
            }
        });
        mDeleteInputV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mInputBox.setText("");
            }
        });
        mContainer.setOnRetryClickListener(new UILoader.OnRetryClickListener() {
            @Override
            public void onRetryClick() {
                if (mSearchPresenters != null) {
                    mSearchPresenters.reSearch();
                    mContainer.updateStatus(
                            UILoader.UIStatus.LOADING

                    );
                }
            }
        });
        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull @NotNull RefreshLayout refreshLayout) {
                LogUtil.d(TAG,"onRefresh");
                // 刷新内容
                mRefreshLayout.finishRefresh(100);
            }
        });

        mRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull @NotNull RefreshLayout refreshLayout) {
                // 加载更多的内容
                LogUtil.d(TAG,"onLoadMore");
                mRefreshLayout.finishLoadMore(100);
                if (mSearchPresenters != null) {
                    mSearchPresenters.loadMore();
                }
            }
        });
    }

    private void switch2Search(String text) {
        if (TextUtils.isEmpty(text)) {
            Toast.makeText(SearchActivity.this ,"搜索内容不内为空",Toast.LENGTH_SHORT).show();
        } else {
            LogUtil.d(TAG,"switch2Search  "+ text);
            mInputBox.setText(text);
            mInputBox.setSelection(text.length());
            if (mSearchPresenters != null) {
                mSearchPresenters.doSearch(text);
            }
            // 改变ui状态
            if (mContainer != null) {
                mContainer.updateStatus(UILoader.UIStatus.LOADING);
            }
        }
    }

    /*
    * 获取联想的关键词
    * */
    private void getSuggestWord(CharSequence keyWords) {
        if (mSearchPresenters != null) {
            mSearchPresenters.getRecommendWord(keyWords.toString());
        }
    }

    private void initView() {
        mBackBtn = this.findViewById(R.id.search_back);
        mInputBox = this.findViewById(R.id.search_input);
        mInputBox.postDelayed(new Runnable() {
            @Override
            public void run() {
                mInputBox.requestFocus();
                mInputMethodManager.showSoftInput(mInputBox,InputMethodManager.SHOW_IMPLICIT);
            }
        },200);
        mSearchBtn = this.findViewById(R.id.search_btn_text);
        mSearchContainer = this.findViewById(R.id.search_container);
        //mFlowTextLayout = this.findViewById(R.id.flow_text_layout);
        if (mContainer == null) {
            mContainer = new UILoader(this) {
                @Override
                protected View getSuccessView(ViewGroup container) {
                    return createSuccessView();
                }
            };
        }
        if (mContainer.getParent() instanceof ViewGroup) {
            ((ViewGroup) mContainer.getParent()).removeView(mContainer); // 不可以重复添加
        }
        mSearchContainer.addView(mContainer);
        mDeleteInputV = findViewById(R.id.search_input_delete);
        mDeleteInputV.setVisibility(View.GONE);


    }
    /*
    * 创建网络OK时的success
    * */
    private View createSuccessView() {
        View resultView = LayoutInflater.from(this).inflate(R.layout.search_result_layout, null);
        //刷新控件
        mRefreshLayout = resultView.findViewById(R.id.search_refresh_layout);
        // 显示热词
        mFlowTextLayout = resultView.findViewById(R.id.recommend_hot_word_view);
        mResultListView = resultView.findViewById(R.id.result_list_view);
        // 是设置布局管理器
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        mResultListView.setLayoutManager(linearLayoutManager);
        mResultListView.addItemDecoration(new RecyclerView.ItemDecoration() { // 添加间隙
            @Override
            public void getItemOffsets(@NonNull @NotNull Rect outRect, @NonNull @NotNull View view, @NonNull @NotNull RecyclerView parent, @NonNull @NotNull RecyclerView.State state) {
                //super.getItemOffsets(outRect, view, parent, state);
                outRect.top = UIUtil.dip2px(view.getContext(),5);
                outRect.bottom = UIUtil.dip2px(view.getContext(),5);
                outRect.left = UIUtil.dip2px(view.getContext(),5);
                outRect.right = UIUtil.dip2px(view.getContext(),5);
            }
        });
        // 设置适配器
        mAlbumAdapter = new RecommendListAdapter();
        mResultListView.setAdapter(mAlbumAdapter);
        // 搜索推荐
        mRecommendRc = resultView.findViewById(R.id.search_recommend_list);
        // 设置布局管理器
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        mRecommendRc.setLayoutManager(layoutManager);
        // 设置适配器
        mRecommendAdapter = new SearchRecommendAdapter();
        mRecommendRc.setAdapter(mRecommendAdapter);


        return resultView;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mSearchPresenters != null) {
            mSearchPresenters.unRegisterViewCallback(this);
            mSearchPresenters = null;
        }
    }

    @Override
    public void onSearchResultLoad(List<Album> albumList) {
        handleSearchResult(albumList);
        // 搜索结果出来时 隐藏键盘
        mInputMethodManager.hideSoftInputFromWindow(mInputBox.getWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);

    }

    private void handleSearchResult(List<Album> albumList) {
        hideSuccessView();
        mResultListView.setVisibility(View.VISIBLE);

        if (albumList != null) {
            if (albumList.size() == 0) {
                // 数据为空
                // todo
                mContainer.updateStatus(UILoader.UIStatus.EMPTY);
            } else { // 不为空就去设置
                mAlbumAdapter.setData(albumList);
                mContainer.updateStatus(UILoader.UIStatus.SUCCESS);
            }
        }
    }

    @Override
    public void onHotWordLoad(List<HotWord> hotWordList) {
        hideSuccessView();
        mFlowTextLayout.setVisibility(View.VISIBLE);
        LogUtil.d(TAG,"hotWordList SIZE :"+ hotWordList.size());
        List<String> hotWords = new ArrayList<>();
        if (mContainer != null) {
            mContainer.updateStatus(UILoader.UIStatus.SUCCESS);
        }
        for (HotWord hotWord : hotWordList) {
            // hotWords.clear();
            String searchWord = hotWord.getSearchword();
            hotWords.add(searchWord);
        }
        // 更新ui
        mFlowTextLayout.setTextContents(hotWords);
        LogUtil.d(TAG,"hot words"+hotWords.toString());

    }

    @Override
    public void onLoadMoreResult(List<Album> albumList, boolean isOkay) {
        // 处理加载更多的结果
        if (mRefreshLayout != null) {
            mRefreshLayout.finishLoadMore();
        }
        if (isOkay) {
            handleSearchResult(albumList);
        } else {
            Toast.makeText(SearchActivity.this,"没有更多的内容了",Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onRecommendWordLoaded(List<QueryResult> kewWordList) {
        // 得到获取到的联想的内容
        // 在ui上进行显示
        LogUtil.d(TAG,"联想的内容 ： "+ kewWordList.size());
        if (mRecommendAdapter != null) {
            mRecommendAdapter.setData(kewWordList);
        }
        if (mContainer != null) {
            mContainer.updateStatus(UILoader.UIStatus.SUCCESS);
        }
        // 控制显示和隐藏
        hideSuccessView();
        mRecommendRc.setVisibility(View.VISIBLE);
    }

    @Override
    public void onError(int errorCode, String errorMsg) {
        if (mContainer != null) {
            mContainer.updateStatus(UILoader.UIStatus.NETWORK_ERROR);

        }
    }

    private void hideSuccessView() {
        mRecommendRc.setVisibility(View.GONE);
        mFlowTextLayout.setVisibility(View.GONE);
        mResultListView.setVisibility(View.GONE);
    }

    @Override
    public void onItemClick(int position, Album album) {
        AlbumDetailPresenter.getInstance().setTargetAlbum(album);
        // item 被点击了,跳转到详情页
        Intent intent = new Intent(this, DetailActivity.class);
        startActivity(intent);
    }
}
